<?php
class Login extends CI_Controller {
	function index() {
		// This method will have the credentials validation
		$this->load->library ( 'form_validation' );
		
		$this->form_validation->set_rules ( 'email', 'email', 'trim|required|xss_clean|valid_email' );
		$this->form_validation->set_rules ( 'password', 'Password', 'trim|required|xss_clean|callback_check_database' );
		
		if ($this->form_validation->run () == FALSE) {
			// Field validation failed. User redirected to login page
			$this->load->view ( 'login_view' );
		} else {
			// Go to private area
			redirect ( 'main_page', 'refresh' );
		}
	}
	function check_database() {
		
		// Field validation succeeded. Validate against database
		$username = $this->input->post ( 'email' );
		$password = md5 ( $this->input->post ( 'password' ));
		// query the database
		$result = $this->user->login ( $username, $password );
		
		if ($result) {
			$sess_array = array ();
			foreach ( $result as $row ) {
				$sess_array = array (
						'user_id' => $row->user_id,
						'user_mail' => $row->user_mail 
				);
				$this->session->set_userdata ( 'logged_in', $sess_array );
				redirect ( 'home', 'refresh' );
			}
			return TRUE;
		} else {
			$this->form_validation->set_message ( 'check_database', 'Invalid username or password' );
			redirect ( 'main_page', 'refresh' );
			return false;
		}
	}
	
	function logout()
	{
		$this->session->unset_userdata('logged_in');
		session_destroy();
		redirect('Main_page', 'refresh');
	}
}